import tornado.web
import tornado.ioloop
import tornado.httpclient
from . import utils
import json
import threading
'''
#1.1声纹处理接口（建库比对）：
本接口进行声纹比对、删除、注册操作，异步方式。

    http://ip:port/receive/model
    {
        "id":"",
        "fileType":"",
        "fileUrl":"",
        "identity":"",
        "job":"",　searchModel,delModel,regModel
        "callbackUrl":"",
        "isReturnModelStr":"false"
    }
    resp:
    {
        "ok":1,"failed":}
    }
    {
        "ok":0,"failed":"失败信息"}
    }
    callback:

'''
class receive_model(tornado.web.RequestHandler):

    def initialize(self, db):
        self.db = db

    def work(self, data:dict, inthread = False):
        if inthread:
            print('work:{}'.format(data))
            callbackdata = {
                "id":data['id'],
                "state":{
                    "ok":1,
                    "failed":""
                },
                "result":""
            }
            try:
                if data['job'] == 'regModel' or data['job'] == 'searchModel':
                    mediaurls = data['fileUrl'].split(',')
                    for url in mediaurls:
                        http_client = tornado.httpclient.HTTPClient()
                        response = http_client.fetch(url)
                        print(response)
                        utils.write2file("receive_model.raw", response.body)
                        http_client.close()

                    if data['job'] == 'regModel':
                        modelstr = utils.getfakeModelStr()
                        if(data['isReturnModelStr'] == 'true'):
                            callbackdata['result'] = modelstr
                        else:
                            self.db.addModel(data['identity'], modelstr)

                    elif data['job'] == 'searchModel':
                        callbackdata['result'] = [
                                                    {
                                                        "identity":"",
                                                        "similarity":0
                                                    },
                                                    {
                                                        "identity":"",
                                                        "similarity":0
                                                    }
                                                ]
                elif data['job'] == 'delModel':
                    self.db.delModel(data['identity'])

                else:
                    callbackdata['state']['ok'] = 0
                    callbackdata['state']['failed'] = "unknown job {}".format(data['job'])

            except BaseException as e:
                callbackdata['state']['ok'] = 0
                callbackdata['state']['failed'] = str(e)


            http_client = tornado.httpclient.HTTPClient()
            try:
                response = http_client.fetch(data['callbackUrl'], method='POST', body=json.dumps(callbackdata), headers = {'Content-Type': 'application/json'})
            except BaseException as e:
                print(e)

        else:
            t = threading.Thread(target=self.work, args=(data, True))
            t.start()


    def post(self, *args, **kwargs):
        resp = None
        try:
            data=json.loads(self.request.body)
            print(data)
            paramerror = utils.checkParam(data, {
                "id":"",
                "fileType":"",
                "fileUrl":"",
                "identity":"",
                "job":"",
                "callbackUrl":"",
                "isReturnModelStr":"false"
            })
            if paramerror == '':
                if data['job'] == 'regModel':
                    modelstr = self.db.getModel(data['identity'])
                    if modelstr:
                        resp = {
                            "ok":0,"failed":'已注册'
                        }
                if not resp:
                    self.work(data)
                    resp = {
                        "ok":1,"failed":''
                    }
            else:
                resp = {
                    "ok":0,"failed": paramerror
                }

        except BaseException as e:
            resp = {
                "ok":0,"failed": str(e)
            }

        self.write(resp)
